import axios from 'axios'
import store from '@/store'
import qs from 'qs'
import {baseUrl} from './config.js'
// create an axios instance
const service = axios.create({
	baseURL:baseUrl,
	// withCredentials: true, // send cookies when cross-domain requests
	timeout: 500000 // request timeout
})
//适配器设置 因为app没有xhrhttprequest 所以需要配置一下
service.defaults.adapter = function (config) {
	return new Promise((resolve, reject) => {
		var settle = require('axios/lib/core/settle');
		var buildURL = require('axios/lib/helpers/buildURL');
		var buildFullPath = require('axios/lib/core/buildFullPath');
		
		let fullurl = buildFullPath(config.baseURL,config.url)
		uni.request({
			method: config.method.toUpperCase(),
			url: buildURL(fullurl, config.params, config.paramsSerializer),
			header: config.headers,
			data: config.data,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			complete:function complete(response){
				response = {
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config: config
				};
				settle(resolve, reject, response);
			}
		})
	})
}
// request interceptor
service.interceptors.request.use(
	config => {
		config.headers['Content-Type'] = 'application/json;charset=UTF-8';
		if (store.getters.token) {
			config.headers['Authorization'] = `Bearer ${store.getters.token}`;
		}
		if(config.method === 'get'){
			//如果是get请求，且params是数组类型如arr=[1,2]，则转换成arr=1&arr=2
			config.paramsSerializer = params =>qs.stringify(params, {arrayFormat: 'repeat'})
		}
		const {data,params} = config;
		if(data&&data.showLoading || params&&params.showLoading) {
			config.data = data&&data.singleData || data;
			config.params = params&&params.singleData || params;
			return config
		}
		// uni.showLoading({
		// 	mask:true,
		// 	title:'玩命加载中...',
		// })
		return config
	},
	error => {
		// do something with request error
		console.log(error) // for debug
		return Promise.reject(error)
	}
)

// response interceptor
service.interceptors.response.use(
	/**
	 * If you want to get http information such as headers or status
	 * Please return  response => response
	 */

	/**
	 * Determine the request status by custom code
	 * Here is just an example
	 * You can also judge the status by HTTP Status Code
	 */
	response => {
		const res = response.data;
		// if the custom code is not 20000, it is judged as an error.
		//uni.hideLoading()
		if (!res || !res.success) {
			const normalTips = '加载失败，网络环境太差了'
			let title = res&&res.msg || normalTips;
			const reg = new RegExp("[\\u4E00-\\u9FFF]+","g"); //如果返回错误不是中文则直接提示加载失败，网络环境太差了
			if(!reg.test(title)) title = normalTips
			uni.showToast({
				title,
				icon: 'none'
			})
			// if(title==='登录过期'){
			// 	uni.navigateTo({
			// 		url:'/pages/organization/organization'
			// 	})
			// }
			// 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
			return Promise.reject(new Error(title || 'Error'))
		} else {
			return res.data;
		}
	},
	error => {
		uni.hideLoading()
		const data = error.response.data || {}
		const message = data.msg || '加载失败，网络环境太差了';
		const code = error.response.data ? error.response.data.code : ''
		console.log(store.getters.failLogin)
		if(code==401&&!store.getters.failLogin){
			store.dispatch('setFailLogin',true)
			let token = store.getters.token
			console.log(token,'555555')
			if(token){
				uni.showModal({
					title:'温馨提示',
					content:'重新过期，请重新登录',
					showCancel:false,
					success() {
						const keyList = uni.getStorageInfoSync().keys.filter(val=>val.indexOf('agreementFlag')===-1);
						keyList.forEach(key => uni.removeStorageSync(key));
						store.dispatch('loginOut');
						store.dispatch('setFailLogin',false)
						uni.reLaunch({
							url:'/pagesB/register/register'
						})
					}
				})
			}
			return Promise.reject(error)
		}
		if(!store.getters.failLogin){
			uni.showToast({
				title:'加载失败，网络环境太差了',
				icon: 'none'
			})
		}
		return Promise.reject(error)
	}
)

export default service
